<script setup>

</script>

<template>
  <el-card>
    <!--条件查询开始-->
    <el-form ref="queryParams" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="所属部门" prop="deptId">
        <el-select
            v-model="queryParams.data.deptId"
            placeholder="请选择部门"
            clearable
            size="small"
            style="width:240px">
          <el-option
              v-for="dict in deptOptions"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
            v-model="queryParams.data.userName"
            placeholder="请输入用户姓名"
            clearable
            size="small"
            style="width:240px"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="queryParams.data.phone"
            placeholder="请输入手机号"
            clearable
            size="small"
            style="width:240px"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="queryParams.data.status"
            placeholder="可用状态"
            clearable
            size="small"
            style="width:240px">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="queryParams.data.dateRange"
            size="small"
            style="width:240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholde="开始日期"
            end-placeholde="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
          批量删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 表格工具按钮结束 -->
    <!-- 数据表格开始 -->
    <el-table v-loading="loading" border :data="userTableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="邮箱：">
              <span>{{ props.row.email }}</span>
            </el-form-item>
            <el-form-item label="擅长：">
              <span>{{ props.row.strong }}</span>
            </el-form-item>
            <el-form-item label="荣耀：">
              <span>{{ props.row.honor }}</span>
            </el-form-item>
            <el-form-item label="简介：">
              <span>{{ props.row.introduction }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="用户ID" align="center" prop="userId"/>
      <el-table-column label="用户姓名" align="center" prop="userName"/>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="手机号码【登陆身份】" width="180" align="center" prop="phone"/>
      <el-table-column label="性别" align="center" prop="sexName"/>
      <el-table-column label="年龄" align="center" prop="age"/>
      <el-table-column label="是否排班" align="center" prop="schedulingFlag">
        <template slot-scope="scope">
          <span v-if="scope.row.schedulingFlag==0">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="级别" prop="rankName" align="center"/>
      <el-table-column label="背景" prop="backgroundName" align="center"/>
      <el-table-column label="状态" prop="statusName" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200"/>
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.userId!=1" type="text" icon="el-icon-delete" size="mini" :disabled="single"
                     @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button v-if="scope.row.userId!=1" type="text" icon="el-icon-thumb" size="mini"
                     @click="handleSelectRole(scope.row)">分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-show="queryParams.total>0"
        :current-page="queryParams.pageNo"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryParams.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 添加弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="addopen"
        width="800px"
        center
        append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="form.userName" style="width:240px" placeholder="请输入用户名称"
                        clearable
                        size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" style="width:240px"
                        placeholder="请输入手机号，作为登陆凭证"
                        clearable size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属科室" prop="deptId">
              <el-select
                  v-model="form.deptId"
                  placeholder="所属科室"
                  clearable
                  size="small"
                  style="width:240px"
              >
                <el-option
                    v-for="d in deptOptions"
                    :key="d.deptId"
                    :label="d.deptName"
                    :value="d.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="级别" prop="userRank">
              <el-select
                  v-model="form.userRank"
                  placeholder="用户级别"
                  clearable
                  size="small"
                  style=" width:240px"
              >
                <el-option
                    v-for="d in lavelOptions"
                    :key="d.dictValue"
                    :label="d.dictLabel"
                    :value="d.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="0" clearable size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背景" prop="background">
              <el-select
                  v-model="form.background"
                  placeholder="学历"
                  clearable
                  size="small"
                  style="width:240px"
              >
                <el-option
                    v-for="d in backGroudOptions"
                    :key="d.dictValue"
                    :label="d.dictLabel"
                    :value="d.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio
                    v-for="d in sexOptions"
                    :key="d.dictValue"
                    :label="d.dictValue"
                    :value="d.dictValue"
                >{{ d.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                    :value="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否参与排班" prop="schedulingFlag">
              <el-radio-group v-model="form.schedulingFlag">
                <el-radio
                    v-for="d in schedulingFlagOptions"
                    :key="d.dictValue"
                    :label="d.dictValue"
                    :value="d.dictValue"
                >{{ d.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" style="width:240px" placeholder="请输入用户邮箱" clearable
                        size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="擅长" prop="strong">
              <el-input v-model="form.strong" type="textarea" placeholder="请输入用户擅长"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="荣誉" prop="honor">
              <el-input v-model="form.honor" type="textarea" placeholder="请输入用户相关荣誉"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="简介" prop="introduction">
              <el-input v-model="form.introduction" type="textarea" placeholder="请输入用户简介"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addhandleSubmit()">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="selectRoleOpen"
        width="900px"
        center
        append-to-body
    >
      <el-table
          v-loading="loading"
          border
          :model="form"
          :data="roleTableOptions"
          @selection-change="handleRoleTableSelectionChange"
          ref="roleTable"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="角色ID" align="center" prop="roleId"/>
        <el-table-column label="角色名称" align="center" prop="roleName"/>
        <el-table-column label="权限编码" align="center" prop="roleCode"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="创建时间" align="center" prop="createTime"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveRoleUserSubmit" :disabled="roleSingle">确 定</el-button>
        <el-button @click="cancelRoleUser">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹出层结束 -->
  </el-card>
</template>
<script>
export default {
  data() {
    return {
      //保留手机号
      myPhone: "",
      // 是否启用遮罩层
      loading: false,
      // 选中数组
      ids: [],
      userIds: [],
      // 非单个禁用
      single: false,
      //role选择非单个禁用
      roleSingle: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        data: {
          /*userName: undefined,
          phone: undefined,
          sex: undefined,
          status: undefined,
          deptId: undefined,
          deptName: undefined,
          deptIds: undefined,*/
        },
        pageNo: 1,
        pageSize: 5,
        total: 0,
      },
      // 部门列表
      deptOptions: [],
      // 状态列表
      statusOptions: [],
      // 表格数据
      userTableList: [],
      // 级别列表
      lavelOptions: [],
      // 背景列表
      backGroudOptions: [],
      //是否确定排班
      schedulingFlagOptions: [],
      // 性别列表
      sexOptions: [],
      //日期范围
      dateRange: [],
      // 是否添加弹出层
      addopen: false,
      // 弹出层标题
      title: '',
      // zengjia表单数据
      form: {},

      // 是否显示分配权限的弹出层
      selectRoleOpen: false,
      // roleIds 分配角色列表选择状态
      roleIds: [],
      // 角色Id用户Id数据字典
      roleUserIds: [],
      //用户角色提交的用户id
      uId: null,
      // 角色数据字典
      roleTableOptions: [],

      // 当前选中的用户
      currentUserId: undefined,

      //表单验证
      rules: {
        userName: [
          {required: true, message: '姓名不能为空', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '所属科室不能为空', trigger: 'blur'}
        ],
        userRank: [
          {required: true, message: '级别不能为空', trigger: 'blur'}
        ],
        // age: [
        //     {required: true, message: '年龄不能为空', trigger: 'blur'}
        // ],
        background: [
          {required: true, message: '学历不能为空', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'}]
      },
    }
  },
  created() {
    this.init()
    this.deptFormatter()
    this.deptDict()
    this.sexDict()
    this.schedulingFlagDict()
    this.userRankDict()
    this.backgroundDict()
    this.statusDict()
    this.getRoleList()
    this.getRoleUserIds()
  },
  methods: {
    //加载表格信息
    init() {
      this.$http.post('/user/getAll', this.queryParams).then(res => {
        this.userTableList = res.data.data.list
        this.queryParams.total = res.data.data.total
      })
    },
    //得到用户id角色id对应字典
    getRoleUserIds() {
      this.$http.get('/user/getRoleUserIds').then(res => {
        this.roleUserIds = res.data.data
        console.log(JSON.stringify(this.roleUserIds)+"++++++++++++++++")
      })
    },
    //role表单选择框触发的方法
    handleRoleTableSelectionChange(selection) {
      this.roleIds = selection.map(item => item.roleId)
      this.roleSingle = selection.length === 0
    },
    //role表单取消按钮触发的方法
    cancelRoleUser() {
      this.selectRoleOpen = false;
      // 清除所有行的选择状态
      this.$nextTick(() => {
        this.selectRoleOpen = false;
        if (this.$refs.roleTable) {
          this.$refs.roleTable.clearSelection();
        }
      });
    },
    //role表单确定按钮触发的方法
    handleSaveRoleUserSubmit() {
      // 清除所有行的选择状态
      this.$nextTick(() => {
        this.selectRoleOpen = false;
        this.uId = null
        if (this.$refs.roleTable) {
          this.$refs.roleTable.clearSelection();
        }
      });
      /*console.log(this.roleIds)
      console.log(this.uId)*/
      // 分配角色提交数据
      console.log(JSON.stringify(this.uId)+"===============")
      console.log(JSON.stringify(this.roleIds)+"===============")
      this.$http.post('/user/updateRoleUser/' + this.uId + "/" + this.roleIds).then(res => {
        if (res.data.code === 200) {
          this.$message.success("分配成功")

        }
        this.getRoleUserIds()
      })
    },
    //分配角色
    handleSelectRole(row) {
      this.title = "分配角色"
      this.selectRoleOpen = true
      this.uId = row.userId
      //根据用户id从字典里查角色id
      this.roleUserIds.find(r1 => {
        let roleTable = []
        let rId = null;
        if (parseInt(r1.userId) === parseInt(row.userId)) {
          rId = r1.roleId
          this.roleTableOptions.find(r2 => {
            if (parseInt(r2.roleId) === parseInt(rId)) {
              //选中表格checkbox
              roleTable.push(r2)
              this.$nextTick(() => {
                if (this.$refs.roleTable) {
                  console.log(r2)
                  // 选中表格checkbox
                  this.$refs.roleTable.toggleRowSelection(r2, true);
                }
              });
            }
          })
        }
      })
    },

    //得到角色表信息
    getRoleList() {
      this.$http.get('/user/getAllRole').then(res => {
        this.roleTableOptions = res.data.data
      })
    },
    // 分页pageSize变化时触发
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.init()
    },
    // 点击上一页  下一页，跳转到哪一页面时触发
    handleCurrentChange(val) {
      this.queryParams.pageNo = val
      this.init()
    },
    handleQuery() {
      this.init()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 5,
        total: 0,
        data:{},
      }
      this.init()
      // location.reload()//页面刷新
    },

    //选择批量删除
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length>1
      this.multiple = !selection.length
    },

    //修改回显
    handleUpdate(row) {
      this.addopen = true
      this.title = "修改用户"
      this.$http.get("/user/selectById/" + row.userId).then(res => {
        this.form = res.data.data
      })
    },
    //确认添加或修改
    addhandleSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$http.post("/user/insertOrUpa", this.form).then(res => {
            if (res.data.code === 200) {
              this.$message.success("操作成功");
              this.form = {}
              this.addopen = false;
              this.$refs.form.resetFields()
              this.init();
            } else {
              this.$message.error("操作失败");
              this.$refs.form.resetFields()
            }
          })
        }
      })
      this.init()
    },
    //取消修改
    cancel() {
      this.addopen = false;
      this.$refs.form.resetFields()
      this.form = {}
    },
    //批量删除或单个删除
    handleDelete(row) {
      let userIds = row.userId || this.ids
      this.$confirm("确认删除选中的项吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http.delete("/user/deleteByIds/" + userIds).then(resp => {
          if (resp.data.code === 200) {
            this.$message.success("删除成功");
            this.init()
          }
        }).catch(error =>{
          this.$message.warning("删除失败");
        })
      }).catch(error => {
        this.$message.warning("取消删除");
      })
    },


    handleAdd() {
      this.addopen = true
      this.title = "添加用户"
      this.form = {}
    },
    deptFormatter(row) {
      let deptLabel = "未知";
      this.deptOptions.filter(item => {
        if (parseInt(item.deptId) === parseInt(row.deptId)) {
          deptLabel = item.deptName
        }
      })
      return deptLabel;
    },
    // 得到部门列表
    deptDict() {
      this.$http.post('/user/getAllDept').then(res => {
        this.deptOptions = res.data.data
      })
    },
    sexFormatter(row) {
      let sexLabel = "未知";
      this.sexOptions.filter(item => {
        if (parseInt(item.dictValue) === parseInt(row.sex)) {
          sexLabel = item.dictLabel
        }
      })
      return sexLabel;
    },
    // 得到性别列表
    sexDict() {
      this.$http.post('/user/getSexList').then(res => {
        this.sexOptions = res.data.data
      })
    },
    schedulingFlagFormatter(row) {
      let schedulingFlagLabel = "未知";
      this.schedulingFlagOptions.filter(item => {
        if (parseInt(item.dictValue) === parseInt(row.schedulingFlag)) {
          schedulingFlagLabel = item.dictLabel
        }
      })
      return schedulingFlagLabel;
    },
    // 排班状态字典
    schedulingFlagDict() {
      this.$http.get('/user/getSchedulingFlag').then(res => {
        this.schedulingFlagOptions = res.data.data
      })
    },
    userRankFormatter(row) {
      let userRankLabel = "未知";
      this.lavelOptions.filter(item => {
        if (parseInt(item.dictValue) === parseInt(row.userRank)) {
          userRankLabel = item.dictLabel
        }
      })
      return userRankLabel;
    },
    // 用户级别字典
    userRankDict() {
      this.$http.get('/user/getUserRank').then(res => {
        this.lavelOptions = res.data.data
      })
    },
    backgroundFormatter(row) {
      let backgroundLabel = "未知";
      this.backGroudOptions.filter(item => {
        if (parseInt(item.dictValue) === parseInt(row.background)) {
          backgroundLabel = item.dictLabel
        }
      })
      return backgroundLabel;
    },
    // 用户学历字典
    backgroundDict() {
      this.$http.get('/user/getBackground').then(res => {
        this.backGroudOptions = res.data.data
      })
    },
    statusFormatter(row) {
      let statusLabel = "未知";
      this.statusOptions.filter(item => {
        if (parseInt(item.dictValue) === parseInt(row.status)) {
          statusLabel = item.dictLabel
        }
      })
      return statusLabel;
    },
    // 用户状态字典
    statusDict() {
      this.$http.get('/user/getStatusList').then(res => {
        this.statusOptions = res.data.data
      })
    }
  }
}


</script>
<style scoped>

</style>